package com.wzu.servlet;

import com.wzu.pojo.Book;
import com.wzu.service.BookService;
import com.wzu.service.BookServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/addBook")
public class AddBookServlet extends HttpServlet {
    private BookService bookService = new BookServiceImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 解决中文乱码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 1. 获取表单提交的数据
        String title = request.getParameter("title");
        String author = request.getParameter("author");
        String publisher = request.getParameter("publisher");
        String publicationYearStr = request.getParameter("publication_year");
        String isbn = request.getParameter("isbn");
        String priceStr = request.getParameter("price");
        String description = request.getParameter("description");
        String categoryIdStr = request.getParameter("category_id");
        String stockQuantityStr = request.getParameter("stock_quantity");
        String availableQuantityStr = request.getParameter("available_quantity");

        try {
            // 2. 组装成 Book 对象
            Book book = new Book();
            book.setTitle(title);
            book.setAuthor(author);
            book.setPublisher(publisher);
            if (publicationYearStr != null && !publicationYearStr.isEmpty()) {
                book.setPublication_year(Integer.parseInt(publicationYearStr));
            }
            book.setIsbn(isbn);
            if (priceStr != null && !priceStr.isEmpty()) {
                book.setPrice(Double.parseDouble(priceStr));
            }
            book.setDescription(description);
            if (categoryIdStr != null && !categoryIdStr.isEmpty()) {
                book.setCategory_id(Integer.parseInt(categoryIdStr));
            }
            if (stockQuantityStr != null && !stockQuantityStr.isEmpty()) {
                book.setStock_quantity(Integer.parseInt(stockQuantityStr));
            }
            if (availableQuantityStr != null && !availableQuantityStr.isEmpty()) {
                book.setAvailable_quantity(Integer.parseInt(availableQuantityStr));
            }

            // 3. 调用 Service 层保存到数据库
            boolean success = bookService.addBook(book);

            if (success) {
                response.getWriter().write("<script>alert('添加成功！');history.back();</script>");
            } else {
                // 保存失败，提示用户
                response.getWriter().write("<script>alert('添加失败，请重试！');history.back();</script>");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("<script>alert('输入数据有误，请检查！');history.back();</script>");
        }
    }
}